import { Scene, Physics, type Types, Math } from "phaser";
import skyImg from "../images/sky.png";
import platformImg from "../images/platform.png";
import starImg from "../images/star.png";
import bombImg from "../images/bomb.png";
import dudeImg from "../images/dude.png";

let platforms: Physics.Arcade.StaticGroup;
let player: Types.Physics.Arcade.SpriteWithDynamicBody;
let cursors: Types.Input.Keyboard.CursorKeys;
let stars: Physics.Arcade.Group;
let scoreText: Phaser.GameObjects.Text;
let score: number = 0;
let bombs: Physics.Arcade.Group;
let gameOver: boolean = false;

export class Main extends Scene {
    preload() {
        // 加载图片
        this.load.image("sky", skyImg);
        this.load.image("platform", platformImg);
        this.load.image("star", starImg);
        this.load.image("bomb", bombImg);
        // 加载雪碧图
        this.load.spritesheet("dude", dudeImg, { frameWidth: 32, frameHeight: 48 });
    }

    create() {
        // 添加背景
        this.add.image(400, 300, "sky");

        // 添加地板组
        platforms = this.physics.add.staticGroup();
        platforms.create(400, 568, "platform").setScale(2).refreshBody();
        platforms.create(600, 400, "platform");
        platforms.create(50, 250, "platform");
        platforms.create(750, 220, "platform");

        // 添加玩家
        player = this.physics.add.sprite(100, 450, "dude");
        // 设置玩家属性
        player.setBounce(0.2);
        player.setCollideWorldBounds(true);

        // 创建玩家动画
        this.anims.create({
            key: "left",
            frames: this.anims.generateFrameNumbers("dude", { start: 0, end: 3 }),
            frameRate: 10,
            repeat: -1,
        });
        this.anims.create({
            key: "turn",
            frames: [{ key: "dude", frame: 4 }],
            frameRate: 20,
        });
        this.anims.create({
            key: "right",
            frames: this.anims.generateFrameNumbers("dude", { start: 5, end: 8 }),
            frameRate: 10,
            repeat: -1,
        });

        // 添加星星组
        stars = this.physics.add.group({
            key: "star",
            repeat: 11,
            setXY: { x: 12, y: 0, stepX: 70 },
        });
        // 每个星星设置随机弹性
        stars.children.iterate((child) => {
            (child as Physics.Arcade.Sprite).setBounceY(Math.FloatBetween(0.4, 0.8));
            return true;
        });

        // 添加文本
        scoreText = this.add.text(16, 16, "score: 0", { fontSize: "32px", color: "#000" });

        // 添加炸弹组
        bombs = this.physics.add.group();

        // 创建键盘事件监听
        cursors = this.input.keyboard.createCursorKeys();

        // 碰撞设置
        console.log(platforms)

        this.physics.add.collider(player, platforms);
        this.physics.add.collider(stars, platforms);
        this.physics.add.collider(bombs, platforms);
        // 收集星星
        this.physics.add.overlap(player, stars, this.collectStar, null, this);
        // 碰撞炸弹
        this.physics.add.collider(player, bombs, this.hitBomb, null, this);
    }

    update() {
        // 游戏结束
        if (gameOver) {
            return;
        }
        // 按左键
        if (cursors.left.isDown) {
            player.setVelocityX(-160);
            player.anims.play("left", true);
        }
        // 按右键
        else if (cursors.right.isDown) {
            player.setVelocityX(160);
            player.anims.play("right", true);
        }
        // 左右键都没按
        else {
            player.setVelocityX(0);
            player.anims.play("turn");
        }
        // 按上键且有玩家下方有接触
        if (cursors.up.isDown && player.body.touching.down) {
            player.setVelocityY(-330);
        }
    }
    // 收集星星
    collectStar(player, star) {
        // 星星禁用并隐藏
        (star as Physics.Arcade.Sprite).disableBody(true, true);
        // 设置分数
        score += 10;
        scoreText.setText(`Score: ${score}`);

        // 当前活跃的星星为0
        if (stars.countActive(true) == 0) {
            // 重新激活每个星星
            stars.children.iterate((child) => {
                let star = child as Physics.Arcade.Sprite;
                star.enableBody(true, star.x, 0, true, true);
                return true;
            });

            // 炸弹的x坐标
            const x = player.x < 400 ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
            // 创建炸弹
            const bomb: Physics.Arcade.Sprite = bombs.create(x, 16, "bomb");
            bomb.setBounce(1);
            bomb.setCollideWorldBounds(true);
            bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
        }
    }
    // 碰撞炸弹
    hitBomb() {
        this.physics.pause();

        player.setTint(0xff0000);
        player.anims.play("turn");

        gameOver = true;
    }
}
